package com.heima.admin.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto dto) {
       /**
        * 1.检查参数
        */
       if (dto==null || StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
       }
        /**
         * 1.根据用户名查询用户
         */
        AdUser user = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        /**
         * 1.查询用户状态
         */
        if (user.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_INVALID);
        }
        /**
         * 1.查询用户密码是否正确
         */
        String password = user.getPassword();
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        if (!password.equalsIgnoreCase(inputPwd)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        /*
        * 用户密码正确后续操作
        **/
        user.setCreatedTime(new Date());
        updateById(user);
        String token = AppJwtUtil.getToken(Long.valueOf(user.getId()));
        Map map = new HashMap<>();
        AdUserVo adUserVo = new AdUserVo();
        BeanUtils.copyProperties(user,adUserVo);
        map.put("user",adUserVo);
        map.put("token",token);
        return ResponseResult.okResult(map);
    }
}
